import {
  _decorator,
  Component,
  Input,
  input,
  instantiate,
  Node,
  Prefab,
  RigidBody2D,
  Vec2,
} from "cc";
import { MoveBg } from "./MoveBg";
import { PipeSpawn } from "./PipeSpawn";
import { GameReadyUI } from "./ui/GameReadyUI";
import { GamePlayUI } from "./ui/GamePlayUI";
import { GameOverUI } from "./ui/GameOverUI";
import GameData from "./GameData";
import { Bird } from "./Bird";

const { ccclass, property } = _decorator;

enum GameState {
  READY = 0,
  PLAYING = 1,
  OVER = 2,
}

@ccclass("GameManager")
export class GameManager extends Component {
  @property(Bird)
  public bird: Bird = null;

  @property(MoveBg)
  public moveBg: MoveBg = null;

  @property(MoveBg)
  public moveLnad: MoveBg = null;

  @property(PipeSpawn)
  public pipeSpawn: PipeSpawn = null;

  @property(GameReadyUI)
  public gameReadyUI: GameReadyUI = null;

  @property(GamePlayUI)
  public gamePlayUI: GamePlayUI = null;

  @property(GameOverUI)
  public gameOverUI: GameOverUI = null;

  public currentState: GameState = GameState.READY;

  public static instance: GameManager = null;

  public static getInstance() {
    return GameManager.instance;
  }
  protected onLoad() {
    GameManager.instance = this;
  }

  protected start() {
    this.switchReady();
  }

  protected update(deltaTime: number) {}

  public switchReady() {
    this.currentState = GameState.READY;
    this.bird.getComponent(Bird).disableBirdControl();
    this.moveBg.disableMoving();
    this.moveLnad.disableMoving();
    this.pipeSpawn.disablePipeSpawn();
  }

  public switchPlay() {
    this.currentState = GameState.PLAYING;
    this.bird.getComponent(Bird).enableBirdControl();
    this.moveBg.enableMoving();
    this.moveLnad.enableMoving();
    this.pipeSpawn.enablePipeSpawn();
    this.gameReadyUI.hide();
    this.gamePlayUI.show();
  }

  public switchOver() {
    if (this.currentState == GameState.OVER) return;
    this.currentState = GameState.OVER;
    this.bird.getComponent(Bird).disableBirdControlNoRigidBody();
    this.moveBg.disableMoving();
    this.moveLnad.disableMoving();
    this.pipeSpawn.disablePipeSpawn();
    this.gamePlayUI.hide();
    this.gameOverUI.show(GameData.getScore(), 2);
    GameData.resetScore();
  }

  public addScore(count: number = 1) {
    GameData.addScore(count);
    this.gamePlayUI.addScore(GameData.getScore());
    console.log("addScore");
  }
}

// TODO
// 游戏结束管道依然能移动
// 游戏结束控制台有警告
// 游戏结束最终分值多次更新的问题
// 游戏结束点击其余位置还能控制小鸟
